package com.coder520.user.controller;

import com.coder520.common.constants.Constants;
import com.coder520.common.resp.ApiResult;
import com.coder520.user.entity.User;
import com.coder520.user.entity.UserElement;
import com.coder520.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author wsq
 *         Created by wsq on 2018-07-21 16:31.
 * @desc 用户控制器
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    /**
     * 用户登陆  Valid 用于参数的校验
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public ApiResult login(@RequestBody @Valid User user, HttpSession session){
        //默认就是登陆成功，如果出现异常会被全局异常处理拦截
        ApiResult<UserElement> result = new ApiResult<>(Constants.RESP_STATUS_OK,"登录成功");

        UserElement ue= userService.login(user);
        if(ue!=null){
            if(session.getAttribute(Constants.REQUEST_USER_SESSION)==null){
                session.setAttribute(Constants.REQUEST_USER_SESSION,ue);
            }
            result.setData(ue);
        }

        return result;
    }

    @RequestMapping("/register")
    public ApiResult register(@RequestBody @Valid User user){
        userService.registerUser(user);

        return new ApiResult(Constants.RESP_STATUS_OK,"注册成功");
    }
}
